#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: fdm=marker fmr={{{,}}} cms=#%s

import os
import sys
import string
import socket
import re

SOAR_DIR=os.environ.get('SOAR_DIR')
sys.path.append(SOAR_DIR+'/common/python')
try:
    from soar import *
except ImportError:
    print >>sys.stderr, """\
Import soar fail 
%s
%s
""" % (sys.exc_value, sys.version)
    sys.exit(1)

class cnfg_info:
    monitor_port=0

def cnfg():
#{{{
    import ConfigParser

    cnfg=os.environ.get('SVCENV_CNFG')
    if not cnfg:
        print "Error: SVCENV_CNFG not set"
        return 1

    try:
        file=open(cnfg, 'r');
    except:
        print "Error: open %s fail" % cnfg
        return 1 

    try:
        parser=ConfigParser.ConfigParser()
        parser.readfp(file)
        cnfg_info.monitor_port=int(parser.get('AGENT', 'MONITOR_PORT'))
    except:
        print "Error: parse %s fail" % cnfg
        return 1

    return 0
#}}}

def call(sock, cmd):
#{{{
    p=cmd.find(" ");
    if p == -1:
        c=cmd
    else:
        c=cmd[:p]
    c=c.upper();
    if c == "EXIT" or c == "QUIT" or c == "BYE":
        return None

    try:
        sock.sendall(cmd+"\r\n")
    except socket.error, e:
        print "send to agent fail"
        return None

    respond=''
    while 1:
        try:
            buf=sock.recv(1024)
        except socket.error, e:
            print "recv from agent fail: %s" % e
            return None
        if not len(buf):
            break
        respond+=buf
        if respond[-5:] == "\r\n.\r\n":
            respond=respond[:len(respond)-5]
            break
    return respond
#}}}

def main(argc, argv):
#{{{
    res=cnfg()
    if res: return 1

    sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect(('localhost', cnfg_info.monitor_port))
    except socket.gaierror, e:
        print "address-related error: %s" % e
        return 1
    except socket.error, e:
        print "connect to agent fail: %s" % e
        return 1

    if argc == 1:
        prompt='> '
        while 1:
            cmd=string.strip(raw_input(prompt))
            if not cmd: continue
            respond=call(sock, cmd)
            if not respond: break
            print respond
    else:
        cmd=string.join(argv[1:], ' ')
        respond=call(sock, cmd)
        if respond:
            print respond

    sock.close()

    return 0
#}}}

if __name__ == '__main__':
    main(len(sys.argv), sys.argv)
